package com.jingtao.product.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.jingtao.common.core.domain.R;
import com.jingtao.common.core.exception.ServiceException;
import com.jingtao.product.dao.*;
import com.jingtao.product.domain.DTO.SkuStockExample;
import com.jingtao.product.domain.Product;
import com.jingtao.product.domain.Result.ProductResult;
import com.jingtao.product.domain.SkuStock;
import com.jingtao.product.domain.vo.*;
import com.jingtao.product.mapper.*;
import com.jingtao.product.service.ProductService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import javax.validation.groups.Default;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @ClassName:
 * @Description:
 * @Author: zengfanzhen
 * @Date: 2024/3/26 19:08:31
 */
@Service
public class ProductServiceImpl implements ProductService {
    private static final Logger LOGGER = LoggerFactory.getLogger(ProductServiceImpl.class);
    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private ProductDao productDao;

    @Autowired
    private MemberPriceDao memberPriceDao;
    @Autowired
    private MemberPriceMapper memberPriceMapper;
    @Autowired
    private ProductLadderDao productLadderDao;
    @Autowired
    private ProductLadderMapper productLadderMapper;
    @Autowired
    private ProductFullReductionDao productFullReductionDao;
    @Autowired
    private ProductFullReductionMapper productFullReductionMapper;
    @Autowired
    private SkuStockDao skuStockDao;
    @Autowired
    private SkuStockMapper skuStockMapper;
    @Autowired
    private ProductAttributeValueDao productAttributeValueDao;
    @Autowired
    private ProductAttributeValueMapper productAttributeValueMapper;
//    @Autowired
//    private CmsSubjectProductRelationDao subjectProductRelationDao;
//    @Autowired
//    private CmsSubjectProductRelationMapper subjectProductRelationMapper;
//    @Autowired
//    private CmsPrefrenceAreaProductRelationDao prefrenceAreaProductRelationDao;
//    @Autowired
//    private CmsPrefrenceAreaProductRelationMapper prefrenceAreaProductRelationMapper;
    @Autowired
    private ProductVertifyRecordDao productVertifyRecordDao;

    /**
     * 添加商品信息
     * @param product
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R addProduct(Product product) {
        // 使用严格的校验
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        Validator validator = factory.getValidator();
        Set<ConstraintViolation<Product>> violations = validator.validate(product, Default.class);

        // 检查校验错误
        if (!violations.isEmpty()) {
            List<String> errorMessages = new ArrayList<>();
            for (ConstraintViolation<Product> violation : violations) {
                errorMessages.add(violation.getMessage());
            }
            // 数据校验错误，直接使用统一异常处理
            throw new ServiceException("数据校验错误");
        }
        // 添加产品到数据库
        try {
            // 添加产品到数据库
            productMapper.addProduct(product);

            //根据促销类型设置价格：会员价格、阶梯价格、满减价格
            Long productId = product.getId();


            return R.ok("商品添加成功");
        } catch (Exception e) {
            // 如果添加过程中出现异常，回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            // 添加商品时发生错误
            throw new ServiceException("添加商品时发生错误");
        }
    }

    @Override
    public List<Product> queryProduct(QueryProductVo queryProductVo) {
        return productMapper.queryProduct(queryProductVo);
    }





    @Override
    public int create(ProductParam productParam) {
        int count;
        //创建商品
        Product product = productParam;
        product.setId(null);
        productMapper.insertSelective(product);
        //根据促销类型设置价格：会员价格、阶梯价格、满减价格
        Long productId = product.getId();
        //会员价格
        relateAndInsertList(memberPriceDao, productParam.getMemberPriceList(), productId);
        //阶梯价格
        relateAndInsertList(productLadderDao, productParam.getProductLadderList(), productId);
        //满减价格
        relateAndInsertList(productFullReductionDao, productParam.getProductFullReductionList(), productId);
        //处理sku的编码
        handleSkuStockCode(productParam.getSkuStockList(),productId);
        //添加sku库存信息
        relateAndInsertList(skuStockDao, productParam.getSkuStockList(), productId);
        //添加商品参数,添加自定义商品规格
        relateAndInsertList(productAttributeValueDao, productParam.getProductAttributeValueList(), productId);
//        //关联专题
//        relateAndInsertList(subjectProductRelationDao, productParam.getSubjectProductRelationList(), productId);
//        //关联优选
//        relateAndInsertList(prefrenceAreaProductRelationDao, productParam.getPrefrenceAreaProductRelationList(), productId);
        count = 1;
        return count;
    }

    @Override
    public ProductResult getUpdateInfo(Long id) {
        return productDao.getUpdateInfo(id);
    }

    @Override
    public int update(Long id, ProductParam productParam) {
        int count;
        //更新商品信息
        Product product = productParam;
        product.setId(id);
        productMapper.updateByPrimaryKeySelective(product);
        //会员价格
        MemberPriceExample pmsMemberPriceExample = new MemberPriceExample();
        pmsMemberPriceExample.createCriteria().andProductIdEqualTo(id);
        memberPriceMapper.deleteByExample(pmsMemberPriceExample);
        relateAndInsertList(memberPriceDao, productParam.getMemberPriceList(), id);
        //阶梯价格
        ProductLadderExample ladderExample = new ProductLadderExample();
        ladderExample.createCriteria().andProductIdEqualTo(id);
        productLadderMapper.deleteByExample(ladderExample);
        relateAndInsertList(productLadderDao, productParam.getProductLadderList(), id);
        //满减价格
        ProductFullReductionExample fullReductionExample = new ProductFullReductionExample();
        fullReductionExample.createCriteria().andProductIdEqualTo(id);
        productFullReductionMapper.deleteByExample(fullReductionExample);
        relateAndInsertList(productFullReductionDao, productParam.getProductFullReductionList(), id);
        //修改sku库存信息
        handleUpdateSkuStockList(id, productParam);
        //修改商品参数,添加自定义商品规格
        ProductAttributeValueExample productAttributeValueExample = new ProductAttributeValueExample();
        productAttributeValueExample.createCriteria().andProductIdEqualTo(id);
        productAttributeValueMapper.deleteByExample(productAttributeValueExample);
        relateAndInsertList(productAttributeValueDao, productParam.getProductAttributeValueList(), id);
//        //关联专题
//        CmsSubjectProductRelationExample subjectProductRelationExample = new CmsSubjectProductRelationExample();
//        subjectProductRelationExample.createCriteria().andProductIdEqualTo(id);
//        subjectProductRelationMapper.deleteByExample(subjectProductRelationExample);
//        relateAndInsertList(subjectProductRelationDao, productParam.getSubjectProductRelationList(), id);
//        //关联优选
//        CmsPrefrenceAreaProductRelationExample prefrenceAreaExample = new CmsPrefrenceAreaProductRelationExample();
//        prefrenceAreaExample.createCriteria().andProductIdEqualTo(id);
//        prefrenceAreaProductRelationMapper.deleteByExample(prefrenceAreaExample);
//        relateAndInsertList(prefrenceAreaProductRelationDao, productParam.getPrefrenceAreaProductRelationList(), id);
        count = 1;
        return count;
    }

    private void handleUpdateSkuStockList(Long id, ProductParam productParam) {
        //当前的sku信息
        List<SkuStock> currSkuList = productParam.getSkuStockList();
        //当前没有sku直接删除
        if(CollUtil.isEmpty(currSkuList)){
            SkuStockExample skuStockExample = new SkuStockExample();
            skuStockExample.createCriteria().andProductIdEqualTo(id);
            skuStockMapper.deleteByExample(skuStockExample);
            return;
        }
        //获取初始sku信息
        SkuStockExample skuStockExample = new SkuStockExample();
        skuStockExample.createCriteria().andProductIdEqualTo(id);
        List<SkuStock> oriStuList = skuStockMapper.selectByExample(skuStockExample);
        //获取新增sku信息
        List<SkuStock> insertSkuList = currSkuList.stream().filter(item->item.getId()==null).collect(Collectors.toList());
        //获取需要更新的sku信息
        List<SkuStock> updateSkuList = currSkuList.stream().filter(item->item.getId()!=null).collect(Collectors.toList());
        List<Long> updateSkuIds = updateSkuList.stream().map(SkuStock::getId).collect(Collectors.toList());
        //获取需要删除的sku信息
        List<SkuStock> removeSkuList = oriStuList.stream().filter(item-> !updateSkuIds.contains(item.getId())).collect(Collectors.toList());
        handleSkuStockCode(insertSkuList,id);
        handleSkuStockCode(updateSkuList,id);
        //新增sku
        if(CollUtil.isNotEmpty(insertSkuList)){
            relateAndInsertList(skuStockDao, insertSkuList, id);
        }
        //删除sku
        if(CollUtil.isNotEmpty(removeSkuList)){
            List<Long> removeSkuIds = removeSkuList.stream().map(SkuStock::getId).collect(Collectors.toList());
            SkuStockExample removeExample = new SkuStockExample();
            removeExample.createCriteria().andIdIn(removeSkuIds);
            skuStockMapper.deleteByExample(removeExample);
        }
        //修改sku
        if(CollUtil.isNotEmpty(updateSkuList)){
            for (SkuStock pmsSkuStock : updateSkuList) {
                skuStockMapper.updateByPrimaryKeySelective(pmsSkuStock);
            }
        }

    }

    /**
     * 建立和插入关系表操作
     *
     * @param dao       可以操作的dao
     * @param dataList  要插入的数据
     * @param productId 建立关系的id
     */
    private void relateAndInsertList(Object dao, List dataList, Long productId) {
        try {
            if (CollectionUtils.isEmpty(dataList)) return;
            for (Object item : dataList) {
                Method setId = item.getClass().getMethod("setId", Long.class);
                setId.invoke(item, (Long) null);
                Method setProductId = item.getClass().getMethod("setProductId", Long.class);
                setProductId.invoke(item, productId);
            }
            Method insertList = dao.getClass().getMethod("insertList", List.class);
            insertList.invoke(dao, dataList);
        } catch (Exception e) {
            LOGGER.warn("创建产品出错:{}", e.getMessage());
            throw new RuntimeException(e.getMessage());
        }
    }


    private void handleSkuStockCode(List<SkuStock> skuStockList, Long productId) {
        if(CollectionUtils.isEmpty(skuStockList))return;
        for(int i=0;i<skuStockList.size();i++){
            SkuStock skuStock = skuStockList.get(i);
            if(StringUtils.isEmpty(skuStock.getSkuCode())){
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                StringBuilder sb = new StringBuilder();
                //日期
                sb.append(sdf.format(new Date()));
                //四位商品id
                sb.append(String.format("%04d", productId));
                //三位索引id
                sb.append(String.format("%03d", i+1));
                skuStock.setSkuCode(sb.toString());
            }
        }
    }
}
